package controller

import (
	"digital/server/common"
	"digital/server/model"
	"digital/server/response"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strconv"
)

// 获取当前社团管理员管理的社团的所有活动
func GetActInfo(ctx *gin.Context) {
	userid := ctx.Query("uid")
	uid, _ := strconv.Atoi(userid) //获得当前社团管理员的uid
	//fmt.Println(uid)
	DB := common.GetDB()

	//注：可能管理多个社团
	var clubInfo []model.UserClub

	err := DB.Where("UID = ? AND Permission = ?", uid, 1).Find(&clubInfo).Error
	if err != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
		log.Println("Error querying user:", err)
		return
	}

	var act []model.Activity
	for _, club := range clubInfo {
		var activities []model.Activity
		err := DB.Where("Cid = ?", club.Cid).Find(&activities).Error
		if err != nil {
			response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
			log.Println("Error querying activities:", err)
			return
		}
		act = append(act, activities...)

	}

	//获取活动的成员名单
	var members [][]model.User

	//获取活动成员的岗位信息（是否为负责人）
	var memberInfo []model.ActivityUser

	var ResultInfo [][]model.ActivityUserInfo

	//遍历act每一个活动，提取每一个活动的Aid，在activityApply表中找活动参与的成员
	for _, eachAct := range act {
		var actMember []model.ActivityUser
		err := DB.Table("activity_users").Where("aid = ?", eachAct.Aid).Find(&actMember).Error
		if err != nil {
			response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
			log.Println("Error querying activities:", err)
			return
		}
		memberInfo = append(memberInfo, actMember...)

		//var users []model.User

		var All []model.ActivityUserInfo

		for _, apply := range actMember {
			var userinfo model.User
			err1 := DB.Where("uid = ?", apply.UID).First(&userinfo).Error
			if err1 != nil {
				response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
				log.Println("Error querying activities:", err1)
				return
			}
			//users = append(users, userinfo)

			AllInfo := model.ActivityUserInfo{
				ActName: eachAct.ATitle, //活动名称
				Status:  apply.Status,
				User:    userinfo,
			}
			All = append(All, AllInfo)
		}
		//members = append(members, users)
		ResultInfo = append(ResultInfo, All)
	}
	// 返回查询结果
	response.Success(ctx, gin.H{"activity": act, "members": members, "All": ResultInfo}, "获取活动信息成功")

}

//还要实现导出活动成员名单

//func
